<?php
namespace app\api\controller;

use app\common\model\Product as ProductModel;
use think\Request;
use app\common\model\ShopCat as ShopCatModel;
use app\common\model\Shop as ShopModel;

class Api{

    public function cat(Request $request){
        $pid = $request->param('pid',0,'intval');

        $cats = ShopCatModel::all(['pid'=>$pid]);
        $cats = collection($cats)->toArray();

        return json($cats);
    }

    public function shopListByCat(Request $request){

        $cat = $request->param('cat');
        $page = $request->param('page',1,'intval');
        $pageSize = $request->param('pagesize',10,'intval');
        $shops = ShopModel::where('cat',$cat)->paginate($pageSize,false,['page'=>$page]);
        $shops = $shops->items();
        $shops = collection($shops)->toArray();

        return json($shops);
    }


    public function getProductList(Request $request){
        $shopid = $request->param('id');
        if(!$shopid){
            return json([]);
        }
        $products = ProductModel::where('shopid',$shopid)->select();
        $products = collection($products)->toArray();
        return json($products);
    }


    public function getProduct(Request $request){
        $id = $request->param('id',0,'intval');
        $product = ProductModel::find($id);
        if(!$product){
            return json([]);
        }
        $product = $product->toArray();
        return json($product);
    }

    public function search(Request $request){
        $keyword = $request->param('keyword','','trim');

        $products = ProductModel::where('name','like','%'.$keyword.'%')->select();

        if(!$products){
            return json([]);
        }

        $products = collection($products)->toArray();
        return json($products);
    }


}